package com.gaotu.demo.transaction.direct;

import com.gaotu.demo.transaction.User;
import com.gaotu.demo.transaction.UserRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class MybatisBasedDirectUserRepository
        implements UserRepository {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;


    @Override
    public void save(User user) {
        SqlSession sqlSession = null;
        try {
            sqlSession = this.sqlSessionFactory.openSession(false);
            sqlSession.insert("com.gaotu.demo.transaction.insert", user);
            sqlSession.commit();
        }catch (Exception e){
            if (sqlSession != null){
                sqlSession.rollback();
            }
        }finally {
            sqlSession.close();
        }

    }

    @Override
    public User getByUserName(String name) {
        Map<String, Object> params = new HashMap<>();
        params.put("user_name", name);

        SqlSession sqlSession = null;
        try {
            sqlSession = this.sqlSessionFactory.openSession(true);
            List<User> users = sqlSession.selectList("com.gaotu.demo.transaction.getByUserName", params);
            return users.size() > 0 ? users.get(0) : null;
        }finally {
            sqlSession.close();
        }
    }
}
